<template>
  <div class="bookDetail">
    <el-button type="primary" @click="goBack">返回</el-button>
    <el-table
      border
      :data="bookShelfList"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="isbn" label="ISBN" align="center">
      </el-table-column>
      <el-table-column prop="coverUrl" label="图片" align="center">
        <template slot-scope="scope">
          <img :src="getSrc(scope.row.coverUrl)" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="bookName" label="书名" align="center">
      </el-table-column>
      <el-table-column prop="callNumber" label="索书号" align="center">
      </el-table-column>
      <el-table-column prop="press" label="出版社" align="center">
      </el-table-column>
      <el-table-column prop="author" label="作者" align="center">
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">在馆</el-tag>
          <el-tag v-if="scope.row.status === 1" type="danger">出借中</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.row)"
            type="text"
            size="small"
            :disabled="scope.row.status !== 0"
            >借书</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "BookDetail",
  data() {
    return {
      bookShelfList: [],
      isbn: this.$route.params.isbn,
    };
  },
  created() {
    this.fetchBookShelf();
  },
  methods: {
    getSrc(coverUrl) {
      if (coverUrl) {
        return coverUrl;
      } else {
        return this.defaultCover;
      }
    },
    async handleClick(row) {
      const response = await this.$request.post("/api/book/borrow", {
        bookshelfId: row.id,
        username: localStorage.getItem("username"),
      });
      console.log(response);
      if (response.code == 200) {
        this.$alert(response.data, "温馨提示", {
          confirmButtonText: "确定",
        });
        this.fetchBookShelf();
      } else {
        this.$message.error(response.message);
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    async fetchBookShelf() {
      const response = await this.$request.get("/api/bookShelf/" + this.isbn);
      if (response.code == 200) {
        this.bookShelfList = response.data;
      }
    },
  },
};
</script>

<style scoped>
/* 让图片自适应单元格宽度 */
.el-table img {
  max-width: 100%; /* 图片最大宽度不超过容器 */
  height: auto; /* 高度自动保持比例 */
  display: block; /* 避免行内元素的额外间距 */
  margin: 0 auto; /* 水平居中 */
}
</style>